<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
</head>
<body>
    <h1>登录</h1>
    <form id="loginForm">
        <label>用户名：<input type="text" name="username" id="username" required></label><br>
        <label>密码：<input type="password" name="password" id="password" required></label><br>
        <button type="submit">登录</button>
        <p>没有用户名密码？点击跳转<a href="/register.html">注册页面</a></p>
    </form>
    <script>
        document.getElementById('loginForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const username = document.getElementById("username").value;
            const password = document.getElementById("password").value;
            
            if (!username || !password) {
                alert("用户名和密码不能为空");
                return;
            }
            
            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    username: username,
                    password: password
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('登录失败');
                }
                return response.text();
            })
            .then(message => {
                alert(message);
                // 登录成功后的操作，例如跳转到首页
                if (message === "登录成功") {
                    window.location.href = "/index.html";
                }
            })
            .catch(error => {
                alert(error.message);
            });
        });
    </script>
</body>
</html>